using System.IO;
using System.Windows.Media;
using Bookvar.ObjectModel;

namespace Bookvar.ServiceModel.Actions
{
    public class SaveFileResourceAction : ResourcePersistenceAction
    {
        private readonly string fileName;

        public SaveFileResourceAction( IPersistenceService persistenceService, MindMap mindmap, 
            IFileResource resource, string fileName )
            : base( persistenceService, mindmap, resource )
        {
            this.fileName = fileName;
        }

        public override void Execute()
        {
            using ( var fileStream = new FileStream( fileName, FileMode.Open, FileAccess.Read ) )
            {
                PersistenceService.SaveFileResourceToPersistence( Mindmap.Key, Resource, fileStream );
            }

            //Note: apply the resource item source to the newly added file resource
            if ( Resource.FileResourceType == FileResourceType.Resource )
            {
                var resource = (Resource) Resource;

                if ( resource.ResourceType == ResourceType.Image )
                {
                    var converter = new ImageSourceConverter();
                    resource.ItemSource = converter.ConvertFrom( fileName );
                }
                else
                {
                    resource.ItemSource = fileName;    
                }
                //resource.ItemSource = PersistenceService.LoadFileResourceFromPersistence( MindMap.Key, resource );
            }
        }

        public override void Undo()
        {
            PersistenceService.RemoveFileResourceFromPersistence( Mindmap.Key, Resource );
        }
    }
}